package com.movecar.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;

import com.movecar.R;

/**
 * 
 * @author Zhao.JQ
 * 
 *         获得云豆动画
 *
 */
public class PopupWindowAnimation {
	private PopupWindow window;
	private Context context;
	private View view;
	private AnimationDrawable anim;

	public PopupWindowAnimation(View view, Context context) {
		this.view = view;
		this.context = context;
		initPopupWindow();
	}

	// 创建一个包含自定义view的PopupWindow
	private void initPopupWindow() {
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View contentView = inflater.inflate(R.layout.popup_window, null);
		ImageView img = (ImageView) contentView.findViewById(R.id.popup_window_img);
		img.setImageResource(R.anim.beans_progress_round);
		anim = (AnimationDrawable) img.getDrawable();
		window = new PopupWindow(context);
		final Resources res = context.getResources();
		img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (window != null && window.isShowing()) {
					window.dismiss();
					anim.stop();
				}
			}
		});
		anim.start();
		// 设置PopupWindow显示和隐藏时的动画
		window.setAnimationStyle(R.style.AnimationFade);
		// 设置PopupWindow的大小（宽度和高度）
		window.setWidth(LayoutParams.MATCH_PARENT);
		window.setHeight(LayoutParams.MATCH_PARENT);
		window.setBackgroundDrawable(new ColorDrawable(res.getColor(android.R.color.transparent)));
		// 设置PopupWindow的内容view
		window.setContentView(contentView);

		// 设置PopupWindow外部区域是否可触摸
		window.setTouchable(true); // 设置PopupWindow可触摸
		window.setFocusable(true);
		window.setOutsideTouchable(true);

		makePopupWindow();

	}

	public void makePopupWindow() {

		window.showAtLocation(view, Gravity.CENTER_VERTICAL, 0, 0);

		new Handler().postDelayed(new Runnable() {
			public void run() {
				if (window != null && window.isShowing()) {
					window.dismiss();
					anim.stop();
				}

			}
		}, 2000);
	}
}